<?php

App::uses('AppModel', 'Model');

/**
 * Camera Model
 *
 */
class Camera extends AppModel {
    public $primaryKey = 'Id';
    
    var $actsAs = array('Containable');
    /**
     * define relationship
     * @var type 
     */
    public $ResolutionX;
    public $ResolutionY;
    public $belongsTo = array(
        'Customer' => array(
            'className' => 'Customers',
            'foreignKey' => 'CustId'
        ),
        'Building' => array(
            'className' => 'Building',
            'foreignKey' => 'BuildId'
        ),
    );
    /**
     * Display field
     *
     * @var string
     */
    public $displayField = 'name';
    /**
     * Validation rules
     *
     * @var array
     */
    public $validate = array(
        'CamID' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'カメラIDを入力してください。',
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'unique' => array(
                'rule' => 'isUnique',
                'required' => 'create',
                'message' => 'このIDが登録されています',
            ),
            'lenght' => array(
                'rule' => array('maxLength', 20),
                'message' => '20桁以下で入力して下さい。'
            ),
            'single_bye'=>array(
                'rule'=>'/^[\w\d\s.,-]*$/',
                'message'=>'英数字で入力してください。'
            ),
        ),
        'CamName' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'カメラ名を入力してください。',
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'lenght' => array(
                'rule' => array('detecedUtf8Character', 100),
                'message' => '100桁以下で入力して下さい。'
            )
        ),
        'UniIp' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'カメラのIPアドレスを入力してください。',
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'checkIp' => array(
                'rule' => '/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/',
                'message' => "IPアドレスの形式を正しく入力してください。",
            ),
            'lenght' => array(
                'rule' => array('maxLength', 50),
                'message' => '50桁以下で入力して下さい。'
            )
        ),
       
        'HttpPort' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'カメラのHttpポットを入力してください。',
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'numeric' => array(
                'rule' => array('numeric'),
            	'message' => 'Httpポットを数字で入力してください。',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'lenght' => array(
                'rule' => array('maxLength', 6),
                'message' => 'HttpPort must be no larger than 6 characters long.'
            ),
            'uniqueHostAndPort'=>array(
                'rule'=>array('uniqueHostAndPort'),
                'message'=>'入力したカメラが登録されています。'
            )
        ),
        'duration' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => '録画期間を入力してください。',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'numeric' => array(
                'rule' => array('numeric'),
            	'message' => '録画期間を数字で入力してください。',
            //'allowEmpty' => true,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'lenght' => array(
                'rule' => array('maxLength', 11),
                'message' => 'duration must be no larger than 11 characters long.'
            )
        ),
        

        
        'UserName' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'カメラのユーザー名を入力してください。',
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'lenght' => array(
                'rule' => array('detecedUtf8Character', 50),
                'message' => 'UserName must be no larger than 200 characters long.'
            ),
            'single_bye'=>array(
                'rule'=>'/^[\w\d\s.,-]*$/',
                'message'=>'ログインIDは、半角英数記号で入力してください'
            ),
        ),
        'Password' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'カメラのパスワードを入力してください。',
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'lenght' => array(
                'rule' => array('detecedUtf8Character', 100),
                'message' => 'Password must be no larger than 100 characters long.'
            )
        ),
        'CustId' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'お客様を選択してください。',
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'BuildId' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => '物件を選択してください。',
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'isCustomer'=>array(
                'rule'=>array('checkBuildingIsCustomer'),
                'message'=>'エトワール 雪谷'
            )
        ),
        'resolution' => array(
            'numeric' => array(
                'rule' => array('numeric'),
            	'message' => '解像度を数字で入力してください。',
            'allowEmpty' => true,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'lenght' => array(
                'rule' => array('maxLength', 50),
                'message' => 'resolution must be no larger than 50 characters long.'
            )
        ),
        'FrameNo' => array(
            'numeric' => array(
                'rule' => array('numeric'),
            'message' => 'フレーム数を数字で入力してください。',
            'allowEmpty' => true,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'lenght' => array(
                'rule' => array('maxLength', 11),
                'message' => 'frame_no must be no larger than 11 characters long.'
            )
        ),
        'ResolutionY'=>array(
             'numeric' => array(
                'rule' => array('numeric'),
                 'message' => 'Is numberic',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'lenght' => array(
                'rule' => array('maxLength', 8),
                'message' => 'ResolutionY must be no larger than 5 characters long.'
            )
        ),
        'ResolutionX'=>array(
            'numeric' => array(
                'rule' => array('numeric'),
                 'message' => 'Is numberic',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'lenght' => array(
                'rule' => array('maxLength', 6),
                'message' => 'ResolutionX must be no larger than 11 characters long.'
            )
        ),
    );
    
    /**
     * 
     */
    public function uniqueHostAndPort(){
        $conditions = array(
                'Camera.UniIp' => $this->data['Camera']['UniIp'],
                'Camera.HttpPort' => $this->data['Camera']['HttpPort'],
        );
        if($this->id){
            $conditions['Camera.Id <> '] = $this->id;
        }
        $result = $this->find('first',array(
            'conditions'=> $conditions
        ));
        if($result){
            return false;
        }else{
            return true;
        }
    }
    /**
     * 
     */
    public function checkBuildingIsCustomer($check){
        App::uses('Building', 'Model');
        $Building =new Building();
        $result=$Building->find('first',array(
            'conditions'=>array(
                'Building.CustId'=>$this->data['Camera']['CustId'],
                'Building.Id'=>$this->data['Camera']['BuildId'],
            )
        ));
        if($result){
            return true;
        }else{
            return false;
        }
    }
    public function checkIp($param, $field){
        if(filter_var($param[$field], FILTER_VALIDATE_IP)){
            return true;
        }
        return false;
    }
    public function detecedUtf8Character($param,$lenght){
        $value=  array_values($param);
        if(strlen(utf8_decode($value['0']))>$lenght)
            return false;
        return true;
    }
    public function beforeSave($options = array()) {
        parent::beforeSave($options);
        foreach ($this->data[$this->alias] as $key => $value) {
            $this->data[$this->alias][$key]=  trim($value);
        }
        return true;
    }

    /**
     * 
     */
    public function getAllCamera($params=null){
        $conditions = array();
        //
       
        if(isset($params['Camera']['CustId']) && $params['Camera']['CustId'] != '0'){
            $conditions['Camera.CustId'] = $params['Camera']['CustId'];
        }
        //
        if(isset($params['Camera']['BuildId']) && $params['Camera']['BuildId'] != '0'){
            $conditions['Camera.BuildId'] = $params['Camera']['BuildId'];
        }
        //
        if(isset($params['Camera']['CamName']) && strlen($params['Camera']['CamName']) > 0){
            $conditions['Camera.CamName like'] = '%'.$params['Camera']['CamName'].'%';
        }
        //
        if(isset($params['Camera']['other']) && strlen($params['Camera']['other']) > 0){
            $params['Camera']['other'] = trim($params['Camera']['other']);
            $conditions['OR'] = array(
                'Camera.CustId like' => '%'.$params['Camera']['other'].'%',
                'Camera.BuildId like' => '%'.$params['Camera']['other'].'%',
                'Camera.CamName like' => '%'.$params['Camera']['other'].'%',
                'Camera.UniIp like' => '%'.$params['Camera']['other'].'%',
                'Camera.HttpPort like' => '%'.$params['Camera']['other'].'%',
                'Camera.Model like' => '%'.$params['Camera']['other'].'%',
                'Camera.CamID like' => '%'.$params['Camera']['other'].'%',
                
                
            );
            
        }
        $user = CakeSession::read("Auth.User");
        if(!$user['IsAdmin']){
            $conditions['Camera.CustId'] = $user['Id'];
        }
        if(count($conditions) > 0){
            $return = $this->find('all',array('conditions' => $conditions,
								'order' => array('Camera.CamID ASC'),
								));
        }else{
            $return = $this->find('all',array(
				'order' => array('Camera.CamID ASC'),
			));
        }
        return $return;
    }
    /*
    public function getListCamera($CustId=null){
        $condition=array();
        if(empty($CustId)){
            $user = CakeSession::read("Auth.User");
            $CustId=$user['CustId'];
        }
        $data = $this->find('list', array(
            'conditions' => array('CustId'=>$CustId), 
            'fields' => array('Id', 'CamName')));
        $data = array_merge(array('0' => 'すべて'), $data);
        return $data;
        
    }*/
     public function getBuildingOfCondition($CustId, $CamId = null) {
         $conditions=array();
         $conditions['Camera.CustId']=$CustId;
         if(!empty($CamId)){
             $conditions['Camera.Id']=$CamId;
         }
        $data = $this->find('all', array('conditions' =>$conditions,
            'fields' => array('Camera.Id','Camera.CamId','Camera.CamName', 'Camera.BuildId','Building.BuildAddress'),
                )
        );
        return $data;
    }
    
    /**
     * 
     */
    public function setFrame($camera){
        if(isset($camera[$this->alias]['FrameNo'])){
            $url = 'http://' . $camera[$this->alias]['UniIp'] . ':' . $camera[$this->alias]['HttpPort'] . '/cgi-bin/encoder?USER=' . $camera[$this->alias]['UserName'] . '&PWD=' . $camera[$this->alias]['Password']."&VIDEO_FPS_NUM=".$camera[$this->alias]['FrameNo'];
            @file_get_contents($url);
        }
        if(isset($camera[$this->alias]['Resolution'])){
            $url = 'http://' . $camera[$this->alias]['UniIp'] . ':' . $camera[$this->alias]['HttpPort'] . '/cgi-bin/encoder?USER=' . $camera[$this->alias]['UserName'] . '&PWD=' . $camera[$this->alias]['Password']."&VIDEO_RESOLUTION=".$camera[$this->alias]['Resolution'];
            @file_get_contents($url);
        }
    }
}
